﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Windows.Forms;

namespace JEdwonTune.Lib {
    public static class XmlHelper {
        public static void BindXml2TreeView(XmlDocument doc, ref TreeView tv) {
            XmlNode root = doc.DocumentElement;
            populateTreeControl(root, tv.Nodes);
        }
        public static void BindXml2TreeView(String xmlPath, ref TreeView tv) {
            XmlDocument doc = new XmlDocument();
            doc.Load(xmlPath);
            BindXml2TreeView(doc, ref tv);
        }
        private static void populateTreeControl(XmlNode root, TreeNodeCollection nodes) {
            foreach (XmlNode node in root) {
                if (node.NodeType != XmlNodeType.Element) continue;
                TreeNode new_child = new TreeNode(GetTreeNodeTitle(node));
                new_child.Tag = node;
                nodes.Add(new_child);
                populateTreeControl(node, new_child.Nodes);
            }
        }
        public static String GetTreeNodeTitle(XmlNode xn) {
            String title = xn.Name;
            if (xn.Attributes["id"] != null) {
                title += " : "+xn.Attributes["id"].Value;
            } else if (xn.Attributes["name"] != null) {
                title += " : " + xn.Attributes["name"].Value;
            }
            return title;
        }
        public static Boolean ReadBooleanAttr(XmlNode node, String Attr, Boolean def) {
            if (node.Attributes[Attr] == null || String.IsNullOrEmpty(node.Attributes[Attr].Value)) {
                return def;
            } else {
                return (node.Attributes[Attr].Value == "yes"
                            || node.Attributes[Attr].Value == "true"
                            || node.Attributes[Attr].Value == "1");
            }
        }
        public static void SetNodeAttrValue(XmlNode node, XmlAttribute attr, String val) {
            if (node.Attributes[attr.Name] != null) {
                node.Attributes[attr.Name].Value = val;
            } else {
                attr.Value = val;
                node.Attributes.Append(attr);
            }
        }
    }
}
